import * as step from '@flow-step/step-toolkit'
import path from 'path'
import fs from 'fs'

export async function setup(flowJobToken: string, serviceConnectionId: string, nugetPrivateRepoConfigPath: string, repoIds: string): Promise<void> {
    const nugetPrivateRepoConfigPathDir = path.dirname(nugetPrivateRepoConfigPath)
    fs.mkdirSync(nugetPrivateRepoConfigPathDir as string, {recursive: true})
    step.exportEnvVar('NUGET_PRIVATE_REPO_CONFIG_PATH', nugetPrivateRepoConfigPath)
    step.info(`export NUGET_PRIVATE_REPO_CONFIG_PATH=${nugetPrivateRepoConfigPath}`)

    const nugetPrivateRepoCertificate = await step.certificate.getNugetPrivateRepoCertificate(flowJobToken, serviceConnectionId, repoIds)
    if (nugetPrivateRepoCertificate === undefined || nugetPrivateRepoCertificate.nugetRepoConfigContent === undefined) {
        throw new Error(`NUGET private repo config content is empty`)
    }

    fs.writeFileSync(nugetPrivateRepoConfigPath, nugetPrivateRepoCertificate.nugetRepoConfigContent)
    step.info(`save nugetPrivateRepoCertificate to ${nugetPrivateRepoConfigPath} successfully!`)

    return
}